package com.itheima.service.impl;

import com.itheima.dao.AccountDao;
import com.itheima.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author huyoufu <https://github.com/huyoufu>
 * @TIME 2020-08-09 09:11
 * @description
 */
@Service
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountDao accountDao;
    @Autowired
    private DataSource dataSource;
    @Override
    public void transfer(String from, String to, double money) {

        //事务相关操作交给连接对象控制的 使用同一个连接!!!!!

        //最终要释放连接
        Connection connection=null;
        try {
            //获取连接 也在service来写!!
            connection = dataSource.getConnection();

            //开启事务
            connection.setAutoCommit(false);

            /************业务代码 开始了*/

            //给from减少
            accountDao.sub(from,money,connection);

            //故意报个异常之类
            int i=5/0;

            //给to增加
            accountDao.add(to,money,connection);


            /************业务代码 结束了*/

            //提交事务
            connection.commit();
        }catch (Exception e){
            e.printStackTrace();

            if (connection!=null){
                try {
                    connection.rollback();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
        }finally {
            if (connection!=null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
